package banners

import (
	"github.com/gin-gonic/gin"
	"google.golang.org/protobuf/types/known/emptypb"
	"mxshop-api/goods-web/api"
	"mxshop-api/goods-web/forms"
	"mxshop-api/goods-web/global"
	"mxshop-api/goods-web/proto"
	"net/http"
	"strconv"
)

/*
*
获取bannerList
*/
func List(ctx *gin.Context) {
	list, err := global.GoodsSrvClient.BannerList(ctx, &emptypb.Empty{})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	result := make([]interface{}, 0)
	for _, value := range list.Data {
		resultMap := make(map[string]interface{})
		resultMap["id"] = value.Id
		resultMap["index"] = value.Index
		resultMap["image"] = value.Image
		resultMap["url"] = value.Url
		result = append(result, resultMap)
	}
	ctx.JSON(http.StatusOK, result)
}

/*
*
创建banner
*/
func New(ctx *gin.Context) {
	bannerForm := forms.BannerForm{}
	err := ctx.ShouldBindJSON(&bannerForm)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	banner, err := global.GoodsSrvClient.CreateBanner(ctx, &proto.BannerRequest{
		Index: int32(bannerForm.Index),
		Image: bannerForm.Image,
		Url:   bannerForm.Url,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	resultMap := make(map[string]interface{}, 0)
	resultMap["id"] = banner.Id
	resultMap["index"] = banner.Index
	resultMap["image"] = banner.Image
	resultMap["url"] = banner.Url
	ctx.JSON(http.StatusOK, resultMap)
}

/*
*
修改banner
*/
func Update(ctx *gin.Context) {
	//校验表单
	bannerForm := forms.BannerForm{}
	err := ctx.ShouldBindJSON(&bannerForm)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	//获取id
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
	}
	//进行修改
	_, err = global.GoodsSrvClient.UpdateBanner(ctx, &proto.BannerRequest{
		Id:    int32(i),
		Index: int32(bannerForm.Index),
		Image: bannerForm.Image,
		Url:   bannerForm.Url,
	})
	//处理返回值
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.Status(http.StatusOK)
}

/*
*
删除banner
*/
func Delete(ctx *gin.Context) {
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
	}
	_, err = global.GoodsSrvClient.DeleteBanner(ctx, &proto.BannerRequest{
		Id: int32(i),
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.Status(http.StatusOK)
}
